package com.jxb.test20241216;

public class Sort5 {

    public static void main(String[] args) {

    }

    public static int[] sortArray(int[] nums) {
        if(nums.length == 0) {
            return nums;
        }

        //构建计数数组
        int max = 0;
        for (int i = 0;i< nums.length;i++) {
            if (nums[i] > max) {
                max = nums[i];
            }
        }
        max = max + 1;
        int[] countArray = new int[max];
        //填充计数数组-将原数组对应的元素值添加到对应的计数数组中
        for (int j=0;j<max;j++) {
            for (int i=0;i<nums.length;i++) {
                if (nums[i] == j) {
                    countArray[j] = countArray[j]+1;
                }
            }
        }
        //根据计数数组，调整原数组-遍历计数数组
        //原数组：[1,4,3,6,0,4,5,9,4,2,6]
        //计数数组：[1,1,1,1,3,1,2,0,0,1]
        int i = 0;
        for (int j=0;j< countArray.length;j++) {
            int count = countArray[j];
            while (count > 0 && i<nums.length) {
                nums[i] = j;
                count--;
                i++;
            }
        }
        return nums;
    }

}
